<template>
  <h4>选择商品【{{ props.goodsName }}】的序列号</h4>
  <!-- 分割线 -->
  <el-divider style="margin: 10px 0" />

  <el-form :model="form" inline>
    <el-form-item label="序列号：">
      <el-input v-model="form.serialNo" placeholder="请输入序列号" style="width: 250px;" />
    </el-form-item>
    <el-form-item label="仓库：">
      <el-input
        v-model="form.warehouseName"
        readonly
        placeholder="所有"
        @click="warehouseVisible = true"
        style="width: 180px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchSerialList">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table
    :data="serialList"
    border
    height="300px"
    ref="serialRef"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="serialNo" label="序列号" width="200" />
    <el-table-column prop="status" label="状态" width="100">
      <template #default="{ row }">
        {{ row.status === 0 ? '未使用' : '已使用' }}
      </template>
    </el-table-column>
    <el-table-column prop="birthday" label="生产日期" width="100" />
    <el-table-column prop="warehouseName" label="仓库" width="100" />
    <el-table-column prop="warehouseLocationName" label="库位" width="100" />
  </el-table>

  <div style="margin-top: 10px; font-size: 14px; color: #606266;">
    已选中 {{ selectedCount }} 个序列号
  </div>

  <el-divider style="margin: 10px 0" />

  <!-- 分页（如果后端分页可改为真实分页） -->
  <div class="page-div" v-if="serialList.length > 10">
    <el-pagination
      :current-page="1"
      :page-size="10"
      :total="serialList.length"
      @current-change="changePage"
      layout="total, ->, prev, pager, next, jumper"
      background
    />
  </div>

  <div style="margin-top: 10px; text-align: right">
    <el-button size="small" @click="emit('update:modelValue', false)">取消</el-button>
    <el-button size="small" type="primary" @click="handleConfirm">确定</el-button>
  </div>

  <!-- 仓库选择弹窗 -->
  <el-dialog
    v-model="warehouseVisible"
    title="仓库搜索列表"
    width="40%"
    draggable
    :show-close="true"
  >
    <WareHouse
      ref="warehouseRef"
      :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }"
    />
    <br /><br />
  </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, onMounted, computed, defineEmits, inject} from 'vue'
import { ElMessage } from 'element-plus'
import WareHouse from '@/views/basic/WareHouse.vue'
let axios = inject("axios")
const props = defineProps(["goodsId", "goodsName"])

const emit = defineEmits(['update:modelValue', 'confirm'])

// 表单
const form = ref({
  serialNo: '',
  warehouseName: '',
  warehouseId: ''
})

// 数据
const serialList = ref([])
const selectedSerial = ref([])
const selectedCount = computed(() => selectedSerial.value.length)

// 仓库弹窗
const warehouseVisible = ref(false)
const warehouseRef = ref()

watch(warehouseVisible, (newVisible) => {
  if (!newVisible && warehouseRef.value?.selectedArray?.length > 0) {
    form.value.warehouseName = warehouseRef.value.selectedArray[0].name
    form.value.warehouseId = warehouseRef.value.selectedArray[0].id
    warehouseRef.value.clearSelected()
  }
})

// 选择变化
const handleSelectionChange = (val) => {
  selectedSerial.value = val
}

// 确认
const handleConfirm = () => {
  emit('confirm', selectedSerial.value)
  emit('update:modelValue', false)
}

// 模拟查询（实际应调用 API）
const searchSerialList = async () => {
  // TODO: 调用接口 this.$api.getSerialList({ goodsName: props.goodsName, serialNo: form.value.serialNo, warehouse: form.value.warehouse })
  // 这里仅演示
  const rs = await axios({
    url: '/xyy/inventory/serialList',
    method: 'post',
    data: {
      serailNo: form.value.serialNo,
      warehouseId: form.value.warehouseId
    }
  })
  console.log(rs)
  // if(rs.data.code == 5200) {

  // }

}

// 分页（前端分页示例）
const changePage = (page) => {
  console.log('跳转到页码:', page)
}

let loading = ref(false);
const init = async () => {
    if (loading.value) return;
    loading.value = true;
    try {
        const rs = await axios({
            url: '/xyy/inventory/serialList',
            method: 'post',
            data: {
                goodsId: props.goodsId,
                serialNo: form.value.serialNo,
                warehouseId: form.value.warehouseId
            }
        })
        if (rs.data.code == 5200) {
            ElMessage({ message: `获取${props.goodsName}的序列号列表成功！`, type: 'success' });
            let arr = [], count = 0;
            rs.data.serialList.forEach(i => {
                let obj = {
                    serialNo: i.serialNo,
                    status: i.status,
                    warehouseId: i.warehouseId,
                    warehouseName: i.warehouseName,
                    warehouseLocationId: i.warehouseLocationId,
                    warehouseLocationName: i.warehouseLocationName,
                }
                arr[count++] = obj;
            })
            console.log("arr:", arr)
            serialList.value = arr;
        }
    }finally {
        loading.value = false;
    }
    

}

// 初始化
onMounted(() => {
  init()
})
</script>

<style scoped>
.page-div {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>